package com.qinggeng.framework.config.mq.impl;
import com.alibaba.fastjson.JSONObject;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.framework.config.mq.dto.MessageAccountDTO;
import com.qinggeng.framework.config.mq.dto.MessageOrderSingleltemDTO;
import com.qinggeng.framework.config.mq.handle.MessageHandle;
import com.qinggeng.project.system.domain.OrdersGoods;
import com.qinggeng.project.system.domain.SinglePointSale;
import com.qinggeng.project.system.domain.SumPointSale;
import com.qinggeng.project.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Slf4j
@Component
public class OrderGoodsSingleItemRefundHandleImpl implements MessageHandle {
    @Resource
    IUserAccountService userAccountService;
    @Autowired
    private IPointSaleService pointSaleService;
    @Autowired
    private IOrdersGoodsService ordersGoodsService;
    @Autowired
    private IOrdersService ordersService;
    @Override
    public void handle(String msg) {
        System.out.println("解析单商品退款handle {}"+msg);

        MessageOrderSingleltemDTO dto=JSONObject.parseObject(msg, MessageOrderSingleltemDTO.class);

        OrdersGoods ordersGoods=ordersGoodsService.selectOrdersGoodsById(dto.getOrdersGoodsId());
        if(null==ordersGoods){
            log.error("订单商品不存在");
            throw new CustomException("订单商品不存在");
        }
        try {
            //单商品退款
            userAccountService.orderGoodsSingleLtemRefund(dto);
            // 更新订单退款金额
            ordersService.updateOrdersPayment(dto.getOrderNo(),dto.getMoney());
        }catch (Exception e){
            throw  new CustomException("錯誤"+e.getMessage());
        }
        try{
            //减少销量统计
            pointSaleService.subtractPointSale(dto.getOrderNo(),ordersGoods.getGoodsId(),ordersGoods.getGoodsNum());
        }catch (Exception e){
            log.error("减少销量统计失败{}",e.getMessage());
        }
    }

}
